from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from recruit.models import Enterprise
from recruit.serializers.Enterprise import *



class EntertpriseHotlistView(ListAPIView):
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseVistSerializers

class EnterpriseIdView(ModelViewSet):
    serializer_class = EnterpriseVistSerializers
    def get_queryset(self):
        pk=self.kwargs.get('pk')
        return Enterprise.objects.filter(pk=pk)

class EnterIdVistView(APIView):
    def put(self, request, pk):
        try:
            Ents=Enterprise.objects.get(pk=pk)
        except Exception as e:
            raise Response("Http404")
        visits=Ents.visits
        new_vis=visits+1
        Ent_dict={'visits':new_vis}
        serializers=EnterpriseVistSerializers(instance=Ents,data=Ent_dict,partial=True)
        rlt=serializers.is_valid()
        if rlt:
            serializers.save()
        return Response({"message":"更新成功","success":True})
class EnterIdCollectView(ModelViewSet):
    queryset = Enterprise.objects.all()
    serializer_class = EnterpriseVistSerializers

    def post(self,request,pk):
        user=request.user
        if not user:
            return Response({'message':'请先登录'})
        ent=self.get_object()
        if user in ent.users.all():
            ent.users.remove(user)
            ent.save()
            return Response({'success': True, 'message': '取消收藏'})
        else:
            ent.users.add(user)
            ent.save()
            return Response({'success': True, 'message': '收藏成功'})



